<!DOCTYPE html>
<html lang="zh-CN" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Waud 监控系统</title>
    <script src="/static/js/echarts.min.js"></script>
    <script src="/static/js/jquery.min.js"></script>
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root {
            --bg-color: #1a1a1a;
            --card-bg: #2d2d2d;
            --text-color: #e0e0e0;
            --border-color: #444;
            --header-bg: #252525;
            --hover-bg: rgba(255, 255, 255, 0.05);
        }

        [data-theme="light"] {
            --bg-color: #f5f5f5;
            --card-bg: #ffffff;
            --text-color: #333333;
            --border-color: #ddd;
            --header-bg: #f8f9fa;
            --hover-bg: rgba(0, 0, 0, 0.05);
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-color);
            padding-top: 20px;
            transition: background-color 0.3s, color 0.3s;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .card {
            background-color: var(--card-bg);
            border: 1px solid var(--border-color);
            margin-bottom: 20px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            overflow: hidden;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
        }

        .card-header {
            background-color: var(--header-bg);
            border-bottom: 1px solid var(--border-color);
            font-weight: 600;
            padding: 15px 20px;
        }

        .chart-container {
            height: 400px;
            width: 100%;
            padding: 15px;
        }

        .small-chart-container {
            height: 300px;
            width: 100%;
            padding: 15px;
        }

        .screenshot-img {
            max-width: 100%;
            height: 180px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            transition: transform 0.3s;
        }

        .screenshot-img:hover {
            transform: scale(1.03);
        }

        .summary-item {
            border-left: 4px solid #007bff;
            padding: 15px;
            margin-bottom: 15px;
            background-color: rgba(0, 123, 255, 0.1);
            border-radius: 0 8px 8px 0;
            transition: background-color 0.3s;
        }

        .summary-item:hover {
            background-color: rgba(0, 123, 255, 0.15);
        }

        .theme-toggle-btn {
            border-radius: 50px;
            padding: 8px 16px;
            margin-bottom: 20px;
        }

        .refresh-btn {
            margin-left: 10px;
            border-radius: 6px;
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: #007bff;
            margin: 10px 0;
        }

        .stat-label {
            font-size: 0.9rem;
            color: #aaa;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        h1, h2, h3, h4, h5, h6 {
            color: var(--text-color);
        }

        .btn-primary {
            background-color: #007bff;
            border-color: #007bff;
            border-radius: 6px;
        }

        .btn-success {
            background-color: #28a745;
            border-color: #28a745;
            border-radius: 6px;
        }

        .btn-warning {
            background-color: #ffc107;
            border-color: #ffc107;
            border-radius: 6px;
        }

        .btn-secondary {
            background-color: #6c757d;
            border-color: #6c757d;
            border-radius: 6px;
        }

        .table {
            color: var(--text-color);
            background-color: var(--card-bg);
        }

        .table th {
            border-top: 1px solid var(--border-color);
            border-bottom: 1px solid var(--border-color);
        }

        .table td {
            border-top: 1px solid var(--border-color);
        }

        .table-hover tbody tr:hover {
            background-color: var(--hover-bg);
        }

        .text-success {
            color: #28a745 !important;
        }

        .text-danger {
            color: #dc3545 !important;
        }

        .navbar-brand {
            color: var(--text-color) !important;
        }

        /* 设备卡片网格布局 */
        .devices-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .device-card {
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .device-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 24px rgba(0,0,0,0.2);
        }

        .device-card-header {
            font-weight: 600;
            margin-bottom: 10px;
            color: #007bff;
        }

        .device-card-body {
            padding: 15px;
        }

        .device-status {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .status-online {
            background-color: rgba(40, 167, 69, 0.2);
            color: #28a745;
        }

        .status-offline {
            background-color: rgba(220, 53, 69, 0.2);
            color: #dc3545;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .container-fluid {
                padding: 0 10px;
            }
            
            .card {
                margin-bottom: 15px;
            }
            
            .chart-container {
                height: 300px;
            }
            
            .small-chart-container {
                height: 250px;
            }
            
            .screenshot-img {
                height: 150px;
            }
            
            .devices-grid {
                grid-template-columns: 1fr;
            }
            
            /* 图表响应式调整 */
            #detectionChart, #screenAnalysisChart, #detectionDistributionChart {
                height: 300px !important;
            }
        }

        @media (max-width: 576px) {
            .chart-container {
                height: 250px;
            }
            
            .small-chart-container {
                height: 200px;
            }
            
            #detectionChart, #screenAnalysisChart, #detectionDistributionChart {
                height: 250px !important;
            }
            
            .screenshot-img {
                height: 120px;
            }
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }

        /* Markdown样式 */
        .markdown-content h1 {
            font-size: 1.75rem;
            margin-top: 1rem;
            margin-bottom: 0.5rem;
        }

        .markdown-content h2 {
            font-size: 1.5rem;
            margin-top: 1rem;
            margin-bottom: 0.5rem;
        }

        .markdown-content h3 {
            font-size: 1.25rem;
            margin-top: 1rem;
            margin-bottom: 0.5rem;
        }

        .markdown-content p {
            margin-bottom: 1rem;
        }

        .markdown-content ul, .markdown-content ol {
            margin-bottom: 1rem;
            padding-left: 2rem;
        }

        .markdown-content li {
            margin-bottom: 0.25rem;
        }

        .markdown-content code {
            background-color: rgba(0, 0, 0, 0.1);
            padding: 0.2rem 0.4rem;
            border-radius: 0.25rem;
            font-size: 0.875em;
        }

        [data-theme="dark"] .markdown-content code {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .markdown-content pre {
            background-color: rgba(0, 0, 0, 0.1);
            padding: 1rem;
            border-radius: 0.25rem;
            overflow-x: auto;
            margin-bottom: 1rem;
        }

        [data-theme="dark"] .markdown-content pre {
            background-color: rgba(255, 255, 255, 0.1);
        }

        .markdown-content blockquote {
            border-left: 4px solid #007bff;
            padding: 0.5rem 1rem;
            margin-bottom: 1rem;
            background-color: rgba(0, 123, 255, 0.1);
            border-radius: 0 0.25rem 0.25rem 0;
        }

        .markdown-content strong {
            font-weight: bold;
        }

        .markdown-content em {
            font-style: italic;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .spinner-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center">
            <h1 class="mb-4">Waud 监控系统</h1>
            <!-- 主题切换按钮 -->
            <button id="themeToggle" class="btn btn-secondary theme-toggle-btn">
                <span class="theme-icon">🌙</span> 暗黑主题
            </button>
        </div>
        
        <!-- 设备统计 -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>设备状态</span>
                        <button id="refreshDevices" class="btn btn-sm btn-primary refresh-btn">
                            刷新
                        </button>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-md-6">
                                <div class="stat-number" id="onlineDevices">0</div>
                                <div class="stat-label">在线设备</div>
                            </div>
                            <div class="col-md-6">
                                <div class="stat-number" id="totalDevices">0</div>
                                <div class="stat-label">总设备数</div>
                            </div>
                        </div>
                        
                        <!-- 设备列表 -->
                        <h5 class="mt-4">设备列表</h5>
                        <div class="devices-grid" id="devicesGrid">
                            <div class="text-center">
                                <div class="spinner-container">
                                    <div class="loading-spinner"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 图表区域 -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>人体检测统计 (最近30天)</span>
                        <button class="btn btn-sm btn-primary refresh-btn" onclick="loadDetectionStats()">
                            刷新
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="detectionChart" class="chart-container"></div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>屏幕分析统计 (最近30天)</span>
                        <button class="btn btn-sm btn-primary refresh-btn" onclick="loadScreenAnalysisStats()">
                            刷新
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="screenAnalysisChart" class="chart-container"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 更多图表 -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>人体检测时间分布 (最近7天)</span>
                        <button class="btn btn-sm btn-primary refresh-btn" onclick="loadDetectionDistribution()">
                            刷新
                        </button>
                    </div>
                    <div class="card-body">
                        <div id="detectionDistributionChart" class="small-chart-container"></div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <span>最新截图</span>
                    </div>
                    <div class="card-body">
                        <div class="row" id="screenshotsContainer">
                            <p class="text-center">加载中...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 每日总结 -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>每日总结</span>
                        <button class="btn btn-sm btn-primary refresh-btn" onclick="loadDailySummaries()">
                            刷新
                        </button>
                    </div>
                    <div class="card-body" id="dailySummaries">
                        <p class="text-center">加载中...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 初始化图表
        var detectionChart = echarts.init(document.getElementById('detectionChart'));
        var screenAnalysisChart = echarts.init(document.getElementById('screenAnalysisChart'));
        var detectionDistributionChart = echarts.init(document.getElementById('detectionDistributionChart'));
        
        // 简单的Markdown解析函数
        function parseMarkdown(text) {
            if (!text) return '';
            
            // 转换代码块
            text = text.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
            
            // 转换行内代码
            text = text.replace(/`([^`]+)`/g, '<code>$1</code>');
            
            // 转换加粗
            text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            
            // 转换斜体
            text = text.replace(/\*(.*?)\*/g, '<em>$1</em>');
            
            // 转换引用
            text = text.replace(/^> (.+)$/gm, '<blockquote>$1</blockquote>');
            
            // 转换标题
            text = text.replace(/^##### (.*$)/gm, '<h5>$1</h5>');
            text = text.replace(/^#### (.*$)/gm, '<h4>$1</h4>');
            text = text.replace(/^### (.*$)/gm, '<h3>$1</h3>');
            text = text.replace(/^## (.*$)/gm, '<h2>$1</h2>');
            text = text.replace(/^# (.*$)/gm, '<h1>$1</h1>');
            
            // 转换无序列表
            text = text.replace(/^\- (.*$)/gm, '<li>$1</li>');
            text = text.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>');
            
            // 转换有序列表
            text = text.replace(/^\d+\. (.*$)/gm, '<li>$1</li>');
            text = text.replace(/(<li>.*<\/li>)/s, '<ol>$1</ol>');
            
            // 转换段落
            text = text.replace(/^\s*(.+?)\s*$/gm, '<p>$1</p>');
            
            // 清理空的段落标签
            text = text.replace(/<p><\/p>/g, '');
            
            return text;
        }
        
        // 主题切换功能
        function toggleTheme() {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            document.documentElement.setAttribute('data-theme', newTheme);
            
            // 更新按钮文本和图标
            const themeToggle = document.getElementById('themeToggle');
            if (newTheme === 'dark') {
                themeToggle.innerHTML = '<span class="theme-icon">🌙</span> 暗黑主题';
            } else {
                themeToggle.innerHTML = '<span class="theme-icon">☀️</span> 明亮主题';
            }
            
            // 重新渲染图表以适应新主题
            setTimeout(() => {
                detectionChart.resize();
                screenAnalysisChart.resize();
                detectionDistributionChart.resize();
            }, 100);
        }
        
        // 获取设备统计信息
        function loadDeviceStats() {
            $.get('/api/device_stats')
                .done(function(data) {
                    $('#onlineDevices').text(data.online);
                    $('#totalDevices').text(data.total);
                })
                .fail(function() {
                    console.error('获取设备统计信息失败');
                });
        }
        
        // 获取设备列表
        function loadDevices() {
            $.get('/api/devices')
                .done(function(data) {
                    let html = '';
                    if (data.length === 0) {
                        html = '<p class="text-center">暂无设备</p>';
                    } else {
                        data.forEach(function(device) {
                            const statusClass = device.status === 'online' ? 'status-online' : 'status-offline';
                            const statusText = device.status === 'online' ? '在线' : '离线';
                            
                            html += `
                                <div class="card device-card" onclick="viewDeviceDetail('${device.id}')">
                                    <div class="device-card-body">
                                        <div class="device-card-header">${device.name}</div>
                                        <div>设备ID: ${device.id}</div>
                                        <div class="mt-2">
                                            <span class="device-status ${statusClass}">${statusText}</span>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                    }
                    $('#devicesGrid').html(html);
                })
                .fail(function() {
                    $('#devicesGrid').html('<p class="text-center text-danger">加载设备列表失败</p>');
                });
        }
        
        // 查看设备详情
        function viewDeviceDetail(deviceId) {
            window.location.href = `/device/${deviceId}`;
        }
        
        // 获取人体检测统计数据
        function loadDetectionStats() {
            $.get('/api/human_detection_stats')
                .done(function(data) {
                    var option = {
                        tooltip: {
                            trigger: 'axis'
                        },
                        legend: {
                            data: ['检测时长(秒)', '检测次数'],
                            textStyle: {
                                color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: data.dates,
                            axisLabel: {
                                color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                            }
                        },
                        yAxis: [
                            {
                                type: 'value',
                                name: '时长(秒)',
                                nameTextStyle: {
                                    color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                                },
                                axisLabel: {
                                    color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                                }
                            },
                            {
                                type: 'value',
                                name: '次数',
                                nameTextStyle: {
                                    color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                                },
                                axisLabel: {
                                    color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                                }
                            }
                        ],
                        series: [
                            {
                                name: '检测时长(秒)',
                                type: 'bar',
                                data: data.durations,
                                itemStyle: {
                                    color: '#5470c6'
                                }
                            },
                            {
                                name: '检测次数',
                                type: 'line',
                                yAxisIndex: 1,
                                data: data.counts,
                                itemStyle: {
                                    color: '#91cc75'
                                },
                                smooth: true
                            }
                        ]
                    };
                    detectionChart.setOption(option, true);
                    
                    // 确保图表在移动端正确显示
                    setTimeout(() => {
                        detectionChart.resize();
                    }, 100);
                })
                .fail(function() {
                    console.error('获取人体检测统计数据失败');
                });
        }
        
        // 获取屏幕分析统计数据（柱状图）
        function loadScreenAnalysisStats() {
            $.get('/api/screen_analysis_stats')
                .done(function(data) {
                    var option = {
                        tooltip: {
                            trigger: 'axis'
                        },
                        legend: {
                            data: ['分析次数'],
                            textStyle: {
                                color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: data.dates,
                            axisLabel: {
                                color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                            }
                        },
                        yAxis: {
                            type: 'value',
                            name: '次数',
                            nameTextStyle: {
                                color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                            },
                            axisLabel: {
                                color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                            }
                        },
                        series: [
                            {
                                name: '分析次数',
                                type: 'bar',
                                data: data.counts,
                                itemStyle: {
                                    color: '#fac858'
                                }
                            }
                        ]
                    };
                    screenAnalysisChart.setOption(option, true);
                    
                    // 确保图表在移动端正确显示
                    setTimeout(() => {
                        screenAnalysisChart.resize();
                    }, 100);
                })
                .fail(function() {
                    console.error('获取屏幕分析统计数据失败');
                });
        }
        
        // 获取人体检测时间分布（7天饼图）
        function loadDetectionDistribution() {
            $.get('/api/detection_distribution')
                .done(function(data) {
                    // 创建7个饼图，每个代表一天的小时分布
                    var option = {
                        tooltip: {
                            trigger: 'item'
                        },
                        legend: {
                            data: data.hours,
                            textStyle: {
                                color: document.documentElement.getAttribute('data-theme') === 'dark' ? '#e0e0e0' : '#333'
                            }
                        },
                        series: [
                            {
                                name: '检测次数',
                                type: 'pie',
                                radius: ['40%', '70%'],
                                data: data.hours.map((hour, index) => ({
                                    name: hour,
                                    value: data.counts[index]
                                })),
                                itemStyle: {
                                    color: function(params) {
                                        const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452'];
                                        return colors[params.dataIndex % colors.length];
                                    }
                                }
                            }
                        ]
                    };
                    detectionDistributionChart.setOption(option, true);
                    
                    // 确保图表在移动端正确显示
                    setTimeout(() => {
                        detectionDistributionChart.resize();
                    }, 100);
                })
                .fail(function() {
                    console.error('获取人体检测时间分布失败');
                });
        }
        
        // 获取每日总结
        function loadDailySummaries() {
            const container = $('#dailySummaries');
            container.html('<p class="text-center">加载中...</p>');
            
            $.get('/api/daily_summary')
                .done(function(data) {
                    if (data.length === 0) {
                        container.html('<p class="text-center">暂无总结</p>');
                        return;
                    }
                    
                    let html = '';
                    data.forEach(function(summary) {
                        html += `
                            <div class="summary-item">
                                <h5>${summary.date}</h5>
                                <div class="markdown-content">
                                    ${parseMarkdown(summary.summary)}
                                </div>
                                ${summary.detailed_analysis ? `
                                    <div class="markdown-content mt-3">
                                        <h6>详细分析</h6>
                                        ${parseMarkdown(summary.detailed_analysis)}
                                    </div>
                                ` : ''}
                            </div>
                        `;
                    });
                    container.html(html);
                })
                .fail(function() {
                    container.html('<p class="text-center text-danger">加载每日总结失败</p>');
                });
        }
        
        // 获取截图（使用Base64编码显示）
        function loadScreenshots() {
            $.get('/api/screenshots')
                .done(function(data) {
                    var html = '';
                    if (!data || data.length === 0) {
                        html = '<p class="text-center">暂无截图</p>';
                    } else {
                        data.forEach(function(item) {
                            // 确保 item 和 base64 字段存在
                            const src = item && item.base64 ? item.base64 : ''; // 占位图
                            const name = item && item.name ? item.name : '未知图片';
                            html += `
                                <div class="col-md-4 mb-3">
                                    <div class="card">
                                        <img src="${src}" class="screenshot-img" alt="${name}">
                                        <div class="card-body">
                                            <p class="card-text text-center">${name}</p>
                                        </div>
                                    </div>
                                </div>
                            `;
                        });
                    }
                    $('#screenshotsContainer').html(html);
                })
                .fail(function() {
                    $('#screenshotsContainer').html('<p class="text-center text-danger">加载失败</p>');
                });
        }
        
        // 页面加载完成后初始化数据
        $(document).ready(function() {
            // 绑定事件
            $('#themeToggle').click(toggleTheme);
            $('#refreshDevices').click(function() {
                loadDeviceStats();
                loadDevices();
            });
            
            // 初始化数据
            loadDeviceStats();
            loadDevices();
            loadDetectionStats();
            loadScreenAnalysisStats();
            loadDetectionDistribution();
            loadDailySummaries();
            loadScreenshots();
            
            // 每30秒刷新一次数据
            setInterval(function() {
                loadDeviceStats();
                loadDevices();
                loadDetectionStats();
                loadScreenAnalysisStats();
                loadDetectionDistribution();
                loadDailySummaries();
                loadScreenshots();
            }, 30000);
            
            // 监听窗口大小变化，调整图表大小
            $(window).resize(function() {
                detectionChart.resize();
                screenAnalysisChart.resize();
                detectionDistributionChart.resize();
            });
        });
    </script>
</body>
</html>